package com.szxb.facebus.util.basics;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.lilei.tool.tool.IToolInterface;
import com.szxb.facebus.BuildConfig;
import com.szxb.facebus.BusApp;
import com.szxb.facebus.intrefaces.OnRxResponse;
import com.szxb.facebus.net.http.RxBaseRequest;
import com.szxb.facebus.scan.DownloadScanRequest;
import com.szxb.facebus.util.rx.MainLooper;
import com.szxb.mlog.SLog;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 作者：Tangren on 2018-03-16
 * 包名：com.szxb.jcbus.util
 * 邮箱：996489865@qq.com
 * TODO:一句话描述
 */

public class AppUtils {

    private static Boolean isDebug = null;

    public static boolean isDebug() {
        return isDebug == null ? false : isDebug;
    }

    public static void syncISDebug(Context context) {
        if (isDebug == null) {
            isDebug = context.getApplicationInfo() != null && (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        }
    }

    /**
     * 获取当前版本名称
     *
     * @param context .
     * @return .
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "0.0.00";
        }
    }

    /**
     * 判断某个Activity 界面是否在前台
     *
     * @param className 类名getName();
     * @return .
     */
    public static boolean isForeground(String className) {
        if (TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) BusApp.getInstance().getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;

    }


    /**
     * 判断某一个类是否存在任务栈里面
     *
     * @return .
     */
    public static boolean isExsitMianActivity(Class<?> cls) {
        Intent intent = new Intent(BusApp.getInstance(), cls);
        ComponentName cmpName = intent.resolveActivity(BusApp.getInstance().getPackageManager());
        boolean flag = false;
        if (cmpName != null) {
            ActivityManager am = (ActivityManager) BusApp.getInstance().getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }


    /**
     * @return 是否有网络
     */
    public static int getNetWorkState() {
        ConnectivityManager connectivityManager = (ConnectivityManager) BusApp.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            String subtypeName = activeNetworkInfo.getSubtypeName();
//            BusApp.getPosManager().setNetSubTypeName(getNetSubTypeName(subtypeName));
            if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                return 1;
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                return 2;
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_ETHERNET)) {
                return 3;
            }
        } else {
            return -1;
        }
        return -1;
    }

    private static String getNetSubTypeName(String type) {
        if (TextUtils.isEmpty(type)) {
            return "UNK";
        }
        switch (type) {
            case "LTE":
                return "4G";
            case "iDen":
            case "GPRS":
            case "EDGE":
            case "CDMA":
                return "2G";
            case "UMTS":
            case "EVDO":
            case "HSDPA":
            case "HSUPA":
            case "HSPA":
            case "eHRPD":
            case "HSPA+":
                return "3G";
            default:
                return "UNK";
        }
    }

    /**
     * @return 内核版本
     */
    public static String getLinuxCore_Ver() {
        InputStream mIS = null;
        BufferedReader mBFR = null;
        String core_Ver = "";
        try {
            mIS = new FileInputStream("/proc/version");//打开文件输入流
            InputStreamReader mISR = new InputStreamReader(mIS); //读取文件输入流内容
            mBFR = new BufferedReader(mISR, 8 * 1024);//使用BufferedReader保存文件输入流的内容
            String line = "";
            while ((line = mBFR.readLine()) != null) { //读取一行
                core_Ver += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (mBFR != null) {
                    mBFR.close();
                }
                if (mIS != null) {
                    mIS.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (core_Ver.length() > 28) {
            return core_Ver.substring(core_Ver.length() - 28, core_Ver.length());
        }
        return core_Ver;
    }


    /**
     * @param lastEntryTime .
     * @return 是否是长按
     */
    public static boolean isLongEntryKey(long lastEntryTime) {
        return (SystemClock.elapsedRealtime() - lastEntryTime < 400);
    }

    /**
     * @param context 。
     * @return 获取推送服务版本
     */
    public static String[] serviceVersionInfo(Context context) {
        //版本号、版本名称
        String[] versionInfo = new String[]{"不存在", "不存在"};
        PackageManager pckMan = context.getPackageManager();
        List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);
        for (PackageInfo info : packageInfo) {
            if (info.packageName.equals("com.szxb.q8server")) {
                versionInfo[0] = info.versionCode + "";
                versionInfo[1] = info.versionName;
            }
        }
        return versionInfo;
    }


    public static void checkUpdate() {
        try {
            int downFinish = BusApp.getPosManager().isDownFinish();
            if (downFinish > 0) {
                final String apkInfo = BusApp.getPosManager().getAPKInfo();
                JSONObject apk = JSONObject.parseObject(apkInfo);
                if (apk.containsKey("apkPath") && apk.containsKey("version")) {
                    final String apkPath = apk.getString("apkPath");
                    String version = apk.getString("version");
                    if (!TextUtils.equals(version, BuildConfig.VERSION_NAME)) {
                        BusApp.getPosManager().setDownFinish(-1);
//                        BusToast.showToast(BusApp.getInstance(), "程序将在1S后自动升级重启", true);
                        MainLooper.getInstance().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                updateApk(apkPath);
                            }
                        }, 1000);
                    } else {
                        BusApp.getPosManager().setDownFinish(-1);
                    }
                } else {
                    BusApp.getPosManager().setDownFinish(-1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            BusApp.getPosManager().setDownFinish(-1);
            SLog.e("AppUtils(checkUpdate.java:253)" + Utils.getExectionStr(e));
        }
    }

    public static void updateApk(String filePath) {
        IToolInterface iToolInterface = BusApp.getInstance().getmService();
        if (iToolInterface != null) {
            try {
                iToolInterface.apkInstall(filePath);
            } catch (RemoteException e) {
                e.printStackTrace();
                SLog.e("AppUtils(updateApk.java:250)更新APK：" + Utils.getExectionStr(e));
            }
        }
    }


    /**
     * @return 二维码任务
     */
    public static List<RxBaseRequest> getScanInit() {
        List<RxBaseRequest> taskList = new ArrayList<>();
        DownloadScanRequest scanRequest = new DownloadScanRequest();
        taskList.add(scanRequest);
        return taskList;
    }


    /**
     * 执行更新任务
     *
     * @param taskList   任务队列
     * @param onResponse 回调
     */
    public static void run(List<RxBaseRequest> taskList, OnRxResponse onResponse) {
        for (Object object : taskList) {
            if (object instanceof DownloadScanRequest) {
                DownloadScanRequest scanRequest = (DownloadScanRequest) object;
                scanRequest.getDisposable();
                scanRequest.setOnResponse(onResponse);
            }
        }
    }

}
